package com.wy.demo.jsonFormat.orgJson;

import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static org.junit.Assert.*;

public class JsonDemo {
    private User3 testUser;
    private File jsonFile;
    private SimpleDateFormat dateFormat;

    @Before
    public void setUp() {
        testUser = new User3(1L, "张三", "zhangsan@example.com", new Date(),
            Arrays.asList("读书", "游泳", "编程"));
        jsonFile = new File("src/main/resources/user.json");
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }

    // 辅助方法：将 JSONArray 转换为 List<String>
    private List<String> jsonArrayToList(JSONArray jsonArray) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            list.add(jsonArray.getString(i));
        }
        return list;
    }

    @Test
    public void testObjectToJsonString() {
        // 对象转 JSON 字符串
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", testUser.getId());
        jsonObject.put("name", testUser.getName());
        jsonObject.put("email_address", testUser.getEmail());
        jsonObject.put("createTime", dateFormat.format(testUser.getCreateTime()));
        jsonObject.put("hobbies", new JSONArray(testUser.getHobbies()));
        
        String jsonString = jsonObject.toString(2); // 2 表示缩进空格数
        System.out.println("对象转 JSON 字符串：");
        System.out.println(jsonString);
        
        assertNotNull(jsonString);
        assertTrue(jsonString.contains("张三"));
        assertTrue(jsonString.contains("email_address"));
    }

    @Test
    public void testJsonStringToObject() {
        // 创建 JSON 字符串
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", testUser.getId());
        jsonObject.put("name", testUser.getName());
        jsonObject.put("email_address", testUser.getEmail());
        jsonObject.put("createTime", dateFormat.format(testUser.getCreateTime()));
        jsonObject.put("hobbies", new JSONArray(testUser.getHobbies()));
        
        String jsonString = jsonObject.toString();
        
        // JSON 字符串转对象
        JSONObject parsedJson = new JSONObject(jsonString);
        User3 parsedUser = new User3();
        parsedUser.setId(parsedJson.getLong("id"));
        parsedUser.setName(parsedJson.getString("name"));
        parsedUser.setEmail(parsedJson.getString("email_address"));
        try {
            parsedUser.setCreateTime(dateFormat.parse(parsedJson.getString("createTime")));
        } catch (Exception e) {
            fail("日期解析失败");
        }
        
        JSONArray hobbiesArray = parsedJson.getJSONArray("hobbies");
        parsedUser.setHobbies(jsonArrayToList(hobbiesArray));
        
        System.out.println("\nJSON 字符串转对象：");
        System.out.println("姓名：" + parsedUser.getName());
        System.out.println("邮箱：" + parsedUser.getEmail());
        
        assertEquals(testUser.getName(), parsedUser.getName());
        assertEquals(testUser.getEmail(), parsedUser.getEmail());
    }

    @Test
    public void testObjectToJsonFile() throws IOException {
        // 对象转 JSON 文件
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", testUser.getId());
        jsonObject.put("name", testUser.getName());
        jsonObject.put("email_address", testUser.getEmail());
        jsonObject.put("createTime", dateFormat.format(testUser.getCreateTime()));
        jsonObject.put("hobbies", new JSONArray(testUser.getHobbies()));
        
        Files.write(Paths.get(jsonFile.getPath()), jsonObject.toString(2).getBytes());
        System.out.println("\n对象已写入文件：" + jsonFile.getAbsolutePath());
        
        assertTrue(jsonFile.exists());
        assertTrue(jsonFile.length() > 0);
    }

    @Test
    public void testJsonFileToObject() throws IOException {
        // 从文件读取 JSON 到对象
        String jsonString = new String(Files.readAllBytes(Paths.get(jsonFile.getPath())));
        JSONObject jsonObject = new JSONObject(jsonString);
        
        User3 fileUser = new User3();
        fileUser.setId(jsonObject.getLong("id"));
        fileUser.setName(jsonObject.getString("name"));
        fileUser.setEmail(jsonObject.getString("email_address"));
        try {
            fileUser.setCreateTime(dateFormat.parse(jsonObject.getString("createTime")));
        } catch (Exception e) {
            fail("日期解析失败");
        }
        
        JSONArray hobbiesArray = jsonObject.getJSONArray("hobbies");
        fileUser.setHobbies(jsonArrayToList(hobbiesArray));
        
        System.out.println("\n从文件读取 JSON 到对象：");
        System.out.println("姓名：" + fileUser.getName());
        System.out.println("爱好：" + fileUser.getHobbies());
        
        assertNotNull(fileUser);
        assertNotNull(fileUser.getName());
        assertNotNull(fileUser.getHobbies());
    }

    @Test
    public void testJsonObjectOperations() {
        // 创建 JSONObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", testUser.getId());
        jsonObject.put("name", testUser.getName());
        jsonObject.put("email_address", testUser.getEmail());
        jsonObject.put("createTime", dateFormat.format(testUser.getCreateTime()));
        jsonObject.put("hobbies", new JSONArray(testUser.getHobbies()));
        
        System.out.println("\nJSONObject 操作：");
        System.out.println("获取 name 字段：" + jsonObject.getString("name"));
        System.out.println("获取 hobbies 数组：" + jsonObject.getJSONArray("hobbies"));
        
        assertTrue(jsonObject.has("name"));
        assertTrue(jsonObject.has("hobbies"));
        assertEquals("张三", jsonObject.getString("name"));
    }

    @Test
    public void testJsonArrayOperations() {
        // 创建用户数组
        User3[] users = new User3[]{
            new User3(1L, "张三", "zhangsan@example.com", new Date(), Arrays.asList("读书", "游泳")),
            new User3(2L, "李四", "lisi@example.com", new Date(), Arrays.asList("篮球", "足球"))
        };
        
        // 数组转 JSON
        JSONArray jsonArray = new JSONArray();
        for (User3 user : users) {
            JSONObject userJson = new JSONObject();
            userJson.put("id", user.getId());
            userJson.put("name", user.getName());
            userJson.put("email_address", user.getEmail());
            userJson.put("createTime", dateFormat.format(user.getCreateTime()));
            userJson.put("hobbies", new JSONArray(user.getHobbies()));
            jsonArray.put(userJson);
        }
        
        String jsonString = jsonArray.toString(2);
        System.out.println("\n数组转 JSON：");
        System.out.println(jsonString);
        
        // JSON 转数组
        JSONArray parsedArray = new JSONArray(jsonString);
        User3[] parsedUsers = new User3[parsedArray.length()];
        
        for (int i = 0; i < parsedArray.length(); i++) {
            JSONObject userJson = parsedArray.getJSONObject(i);
            User3 user = new User3();
            user.setId(userJson.getLong("id"));
            user.setName(userJson.getString("name"));
            user.setEmail(userJson.getString("email_address"));
            try {
                user.setCreateTime(dateFormat.parse(userJson.getString("createTime")));
            } catch (Exception e) {
                fail("日期解析失败");
            }
            
            JSONArray hobbiesArray = userJson.getJSONArray("hobbies");
            user.setHobbies(jsonArrayToList(hobbiesArray));
            
            parsedUsers[i] = user;
        }
        
        System.out.println("\nJSON 转数组：");
        for (User3 user : parsedUsers) {
            System.out.println("姓名：" + user.getName());
        }
        
        assertEquals(2, parsedUsers.length);
        assertEquals("张三", parsedUsers[0].getName());
        assertEquals("李四", parsedUsers[1].getName());
    }
} 